package com.demo.common.dynamic.datasource.config;

import com.demo.common.dynamic.datasource.constants.DataSourceNameConstants;

import com.demo.common.dynamic.datasource.utils.DynamicDataSource;
import lombok.extern.slf4j.Slf4j;

import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * 多数据源配置
 *
 * @author molong
 * @date 2021/10/22
 */
//@Configuration
@EnableConfigurationProperties({DataSourceProperties.class})
@Slf4j
public class MultiDataSourceConfig {

    /**
     * 多数据源动态切换
     * @param dataSourceProperties  主数据源配置
     * @return 多数据源实例
     */
    @Bean
    public DataSource multiDataSource(DataSourceProperties dataSourceProperties) {
        //主数据源
        DataSource masterDataSource=dataSourceProperties.initializeDataSourceBuilder().build();
        DynamicDataSource dataSource = DynamicDataSource.getInstance();
        dataSource.setDefaultTargetDataSource(masterDataSource);
        dataSource.addDataSource(DataSourceNameConstants.MASTER, masterDataSource);
        return dataSource;
    }

}
